// --------------------------------------------------------------------------------------------------------------------
// <copyright file="GroundTruthFromStopAndGoFileAgent.cs" company="Microsoft Corporation">
// The MIT License (MIT)
// 
// Copyright (c) 2014, Microsoft Corporation
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Test.Robotics.Navigation
{
    using System;
    using System.Collections.Concurrent;
    using System.Collections.Generic;
    using System.IO;
    using System.Runtime.Serialization;
    using System.Threading;
    using Microsoft.Robotics.Interaction.Runtime.Input;
    using Microsoft.Robotics.Numerics;
    using Microsoft.Robotics.Runtime;    

    /// <summary>
    /// Agent that calculates the metrics of SLAM.
    /// </summary>
    [DataContract]
    [System.Diagnostics.CodeAnalysis.SuppressMessage(
    "Microsoft.Design",
    "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable",
    Justification = "Agents clean up resources when OnDeactivated() is called")]
    public class GroundTruthFromStopAndGoFileAgent : ConsumerProducerAgent<GamePadAgentMessage, GroundTruthMessage>
    {
        /// <summary>
        /// The maximum number of messages we read in advance, to make sure we have something to publish.
        /// </summary>
        private const int BufferSize = 1;

        /// <summary>
        /// The name of the input file to read ground truth data from
        /// </summary>
        [DataMember(Name = "File")]
        private readonly string fileName;

        /// <summary>
        /// The last GamePad state information.
        /// </summary>
        private GamePadAgentMessage.GamePadAgentButtons lastGamePadState;
        
        /// <summary>
        /// reader for the ground truth data file
        /// </summary>
        private ExternalDatasetGroundTruthFileReader reader;

        /// <summary>
        /// Collection of ground truth messages waiting to be published
        /// </summary>
        private BlockingCollection<AgentMessage> publishingQueue;

        /// <summary>
        /// The thread that does the reading of files.
        /// </summary>
        private Thread fileReaderThread;

        /// <summary>
        /// Initializes a new instance of the GroundTruthFromStopAndGoFileAgent class
        /// </summary>
        /// <param name="name">Agent name</param>
        /// <param name="producer">Producer to subscribe to</param>
        /// <param name="groundTruthFile">The file containing the ground truth info.</param>
        public GroundTruthFromStopAndGoFileAgent(string name, IProducer<GamePadAgentMessage> producer, string groundTruthFile)
            : base(name, producer.Name)
        {
            this.fileName = groundTruthFile;
        }

        /// <summary>
        /// Acts as de-facto constructor, because the agent can be activated/deactivated multiple times in a metrics run
        /// </summary>
        public override void OnActivated()
        {
            base.OnActivated();
            this.publishingQueue = new BlockingCollection<AgentMessage>(BufferSize);
            this.reader = new ExternalDatasetGroundTruthFileReader();
            this.reader.Initialize(this.fileName, this.publishingQueue);

            // Start a background thread to read messages
            this.fileReaderThread = new Thread(this.reader.Start);
            this.fileReaderThread.Name = this.Name;
            this.fileReaderThread.Start();
        }

        /// <summary>
        /// Acts as the de-facto destructor, because the agent can be activated/deactivated multiple times in a metrics run
        /// </summary>
        public override void OnDeactivated()
        {
            this.reader.Stop();
            this.fileReaderThread.Join();
            this.publishingQueue.Dispose();
            base.OnDeactivated();
        }

        /// <summary>
        /// Called when the agent receives a message
        /// </summary>
        /// <param name="gamepadFeedback">The received message</param>
        public override void Receive(GamePadAgentMessage gamepadFeedback)
        {
            if (this.lastGamePadState == null)
            {
                this.lastGamePadState = gamepadFeedback.Buttons;
            }

            // left button is pressed when the robot stops at a marker position
            // when left button is pressed, there will be multiple messages coming all having left pressed
            // we are targeting at the last one, and the one after last one should be left not pressed
            if (this.lastGamePadState.LeftShoulder && !gamepadFeedback.Buttons.LeftShoulder)
            {
                AgentMessage message;
                if (this.publishingQueue.TryTake(out message))
                {
                    // Update the timestamp and send
                    GroundTruthMessage originalMessage = (GroundTruthMessage)message;
                    GroundTruthMessage newMessage = new GroundTruthMessage(originalMessage.PoseId, originalMessage.StartPoseId, originalMessage.DeltaPose, gamepadFeedback.OriginatingTime);
                    this.Publisher.Post(newMessage);
                }
            }

            this.lastGamePadState = gamepadFeedback.Buttons;
        }
    }
}
